<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="6" v-for="(product, index) in products" :key="index">
        <el-card :body-style="{ padding: '0px' }" class="product-card">
          <div class="image-container">
            <img :src="product.image" class="image" />
          </div>
          <div style="padding: 14px">
            <span>{{ product.name }}</span>
            <div class="bottom">
              <span class="price">¥{{ product.price }}</span>
              <el-button type="text" class="button">查看详情</el-button>
              <el-button type="text" class="button" @click="addToCar(product)"
                >加入购物车</el-button
              >
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      products: [
        {
          id: "1001",
          name: "固本延龄丸",
          price: 37,
          description: "本品为黑褐色的小蜜丸；味先甜而后微苦",
          image:
            "https://img01.yilianmeiti.com/project/medicine/2024/09/11/14/9d1270e19101000064ecbc1c23170000.png",
          num: 0,
        },
        {
          id: "1002",
          name: "参术儿康糖浆",
          price: 15,
          description: "本品为棕黄色的黏稠液体;气香，味甜",
          image:
            "https://img01.yilianmeiti.com/project/medicine/2024/04/17/16/d51dffec8e01000064ecbcac077a0000.png",
          num: 0,
        },
        {
          id: "1003",
          name: "三七胶囊",
          price: 30,
          description: "三七胶囊",
          image:
            "https://img01.yilianmeiti.com/project/medicine/2021/12/04/17/626665867d0100001ca552e011c86400.jpeg",
          num: 0,
        },
      ],
    };
  },
  methods: {
    addToCar(e) {
      this.$message.success("添加" + e.name + "到购物车成功");
      let flag = false;
      if (localStorage.getItem("carList")) {
        let carList = JSON.parse(localStorage.getItem("carList"));
        for (let index = 0; index < carList.length; index++) {
          if (e.id == carList[index].id) {
            carList[index].num++;
            flag = true;
          }
        }
        if (!flag) {
          carList.push(e);
        }
        localStorage.setItem("carList", JSON.stringify(carList));
      } else {
        let carList = [];
        carList.push(e);
        localStorage.setItem("carList", JSON.stringify(carList));
      }
    },
  },
};
</script>

<style>
.product-card {
  margin-bottom: 20px;
}

.image-container {
  width: 100%;
  height: 180px; /* 固定高度 */
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f9f9f9; /* 提供背景颜色避免加载失败时出现空白 */
}

.image {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持比例，不会变形 */
  display: block;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 18px;
  color: #f56c6c;
}

.button {
  padding: 0;
  min-height: auto;
}
</style>
